__author__ = 'jason'

import werobot

from plugins import tuling


# import os
# WEIXIN_TOKEN = os.environ.get('WEIXIN_TOKEN')
# print(WEIXIN_TOKEN)
#
# robot = werobot.WeRoBot(token=WEIXIN_TOKEN)
#
#
# def answer_message(info):
#     result = tuling.Query(info).parser()
#
#     if not result['success']:
#         return '阿仁头脑转不过来'
#
#     if result['type'] == 'text':
#         return result['text']
#     if result['type'] == 'link':
#         return result['text'] + result['url']
#     else:
#         return '其他类型'
#
#
# @robot.text
# def text_handle(message):
#     info = message.content
#     return answer_message(info)
#
#
# @robot.voice
# def voice_handle(message):
#     info = message.recognition
#     return answer_message(info)
#
#
# def run():
#     robot.run(server='gunicorn', port='12233')


class Herim(object):
    """
        automatically wechat reply machine
    """

    def __init__(self, token, logger=None, enable_session=True, session_storage=None):
        self.robot = werobot.WeRoBot(token=token, logger=logger, enable_session=enable_session,
                                     session_storage=session_storage)

        @self.robot.text
        def text_handle(message):
            info = message.content
            return Herim.reply_simple_msg(Herim.query_info(info))

        @self.robot.voice
        def text_handle(message):
            info = message.recognition
            return Herim.reply_simple_msg(Herim.query_info(info))

    @staticmethod
    def get_msg_text(message):
        if message['type'] == 'text':
            return message.content
        elif message['type'] == 'voice':
            return message.recognition
        else:
            return ''

    @staticmethod
    def query_info(info):
        result = tuling.Query(info).parser()
        return result

    @staticmethod
    def reply_simple_msg(queried):
        if not queried['success']:
            return '阿仁头脑转不过来'

        if queried['type'] == 'text' or queried['type'] == 'link':
            return Herim.generate_text_reply(queried)

        elif queried['type'] == 'news':
            return Herim.generate_news_reply(queried)

        elif queried['type'] == 'train':
            return Herim.generate_train_reply(queried)

        elif queried['type'] == 'recipe':
            return Herim.generate_recipe_reply(queried)

        else:
            return ''

    @staticmethod
    def generate_text_reply(queried):
        reply_text = ''
        if 'text' in queried.keys():
            reply_text += queried['text']
        if 'url' in queried.keys():
            reply_text += queried['url']
        return reply_text

    @staticmethod
    def generate_news_reply(queried):
        articles = list()

        """ 源数据实例
        "list": [
            {
              "article": "正播女排世界杯 中国VS韩国",
              "source": "网易新闻",
              "icon": "http://img6.cache.netease.com/3g/2015/8/26/201508261520572d7e2.jpg",
              "detailurl": "http://3g.163.com/touch/article.html?from=sports&docid=B1S44PN600051CAQ"
            },
            {
              "article": "英媒赞暴力鸟任意球C罗也得服",
              "source": "网易新闻",
              "icon": "http://img2.cache.netease.com/3g/2015/8/26/20150826122510d2184.jpg",
              "detailurl": "http://3g.163.com/ntes/special/00340EPA/wapSpecialModule.html?sid=S1424154998473"
            }
        ]
        """

        for index, news in enumerate(queried['list']):
            if index >= 10:
                pass
            else:
                # [
                #     "title",
                #     "description",
                #     "img",
                #     "url"
                # ],
                articles.append(
                    [
                        news['article'],
                        news['source'],   # it seems this field doesnt work
                        news['icon'],
                        news['detailurl']
                    ]
            )
        return articles

    @staticmethod
    def generate_train_reply(queried):
        # http://touch.qunar.com/h5/train/
        #  "list":[{
        #     "trainnum":"",
        #     "start":"",
        #     "terminal":"",
        #     "starttime":""
        #     "endtime":""
        #     "detailurl":""
        #     "icon":""
        # }]
        articles = [
            [
                '列车时刻表',
                '阿仁出品',   # it seems this field doesnt work
                'http://p2.qhimg.com/t01ccfd85808d42f6b0.jpg',
                'http://touch.qunar.com/h5/train/'
            ]
        ]

        for index, train in enumerate(queried['list']):
            if index >= 9:
                pass
            else:
                articles.append(
                    [
                        '%s : %s %s - %s %s' % (train['trainnum'], train['start'], train['starttime'], train['terminal'],
                                                train['endtime']),
                        '阿仁出品',
                        train['icon'],
                        train['detailurl']
                    ]
                )

        return articles

    @staticmethod
    def generate_recipe_reply(queried):
        # "list":[{
        #     "name":"",
        #     "info":"",
        #     "detailurl":""
        #     "icon":""
        # }]
        articles = [
            [
                '菜谱',
                '阿仁大厨',   # it seems this field doesnt work
                'http://img1.imgtn.bdimg.com/it/u=73221715,2704757004&fm=21&gp=0.jpg',
                'http://www.meishichina.com'
            ]
        ]
        for index, recipe in enumerate(queried['list']):
            if index >= 9:
                pass
            else:
                articles.append(
                    [
                        recipe['name'] + '|' + recipe['info'],
                        '阿仁大厨',
                        'icon',
                        'detailurl'
                    ]
                )
        return articles

    def run(self, server='gunicorn', port='12233'):
        self.robot.run(server=server, port=port)
